package middleware

import (
	"bgs/util"
	"context"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// UnaryRecoveryInterceptor recovery
func UnaryRecoveryInterceptor(slog *zap.SugaredLogger) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		clog := util.NewContextLogger(ctx, slog)
		panicked := true
		clog.Infof("enter-recovery::")
		defer func() {
			if r := recover(); r != nil || panicked {
				err = status.Errorf(codes.Internal, "%v", r)
				clog.Errorf("exit-recovery::%v", err)
			}
		}()
		resp, err = handler(ctx, req)
		panicked = false
		return resp, err
	}
}
